<?php


namespace app\api\controller\v1;


use app\admin\model\UserModel;
use app\common\RefreshToken;
use app\common\Token;
use app\BaseController;

class User extends BaseController
{
    /** 登录
     * @param string $email
     * @param string $password
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(string $email, string $password)
    {
        $user = new UserModel();
        // 校验账号密码
        $user_info = $user->checkUserInfo($email, $password);
        // 生成新的token
        $jwtToken = Token::setToken($email, $user_info['id']);
        $refreshToken = RefreshToken::setRefreshToken($email, $user_info['id']);
        $user->updateToken($email, $jwtToken, $refreshToken, $this->request->ip());
        return successJson([
            'token' => $jwtToken,
            'refresh_token' => $refreshToken,
        ], '登陆成功');
    }

    /**
     * 通过RefreshToken获取jwtToken
     * @return \think\response\Json
     */
    public function refreshToken()
    {
        $jwtToken = RefreshToken::getJWTToken($this->request);
        return successJson(
            [
                "token" => $jwtToken,
            ]
        );
    }

    /**
     * 取消token
     * @return \think\response\Json
     */
    public function cancelToken(){
        return successJson(Token::cancelToken($this->request));
    }
}